import React, { useEffect, useState } from 'react';
import { Card, Table, Button, DialogPlugin, MessagePlugin, Input, Select, Tag } from 'tdesign-react';
import { AddIcon, EditIcon, DeleteIcon, RefreshIcon } from 'tdesign-icons-react';
import { JupiterUrlResource, JupiterUrlResourceQuery } from '../../types/urlResourceTypes';
import { formatTime } from '../../utils/timeutil';
import {
  fetchUrlResourceList,
  createUrlResource,
  updateUrlResource,
  deleteUrlResource,
} from '../../services/urlResourceService';
import UrlResourceForm from './components/UrlResourceForm';

import DictionarySelect from '../../components/Dictionary/DictionarySelect';

const { Option } = Select;

export default function UrlResourcePage() {
  const [urlResourceList, setUrlResourceList] = useState<JupiterUrlResource[]>([]);
  const [loading, setLoading] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [editingUrlResource, setEditingUrlResource] = useState<Partial<JupiterUrlResource>>();
  const [title, setTitle] = useState('新增URL资源');
  const [searchUrl, setSearchUrl] = useState('');
  const [searchMethod, setSearchMethod] = useState('');
  const [searchModule, setSearchModule] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const getList = async () => {
    setLoading(true);
    try {
      const params = {
        url: searchUrl,
        method: searchMethod,
        module: searchModule,
        page: pagination.current,
        size: pagination.pageSize,
      };
      const res = await fetchUrlResourceList(params);
      if (res.data?.records) {
        setUrlResourceList(res.data.records || []);
        setPagination(prev => ({
          ...prev,
          total: res.data.total || 0,
        }));
      }
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingUrlResource(undefined);
    setTitle('新增URL资源');
    setFormVisible(true);
  };

  const handleEdit = (record: JupiterUrlResource) => {
    setEditingUrlResource(record);
    setTitle('编辑URL资源');
    setFormVisible(true);
  };

  const handleDelete = (record: JupiterUrlResource) => {
    const confirmDialog = DialogPlugin.confirm({
      header: '确认删除',
      body: `确定要删除URL资源 "${record.url}" 吗？`,
      onConfirm: async () => {
        try {
          await deleteUrlResource(record.uuid);
          MessagePlugin.success('删除成功');
          getList();
        } catch (error) {
          MessagePlugin.error('删除失败');
        }
        confirmDialog.destroy();
      },
    });
  };

  const handleSubmit = async (data: Partial<JupiterUrlResource>) => {
    try {
      if (editingUrlResource?.uuid) {
        await updateUrlResource(editingUrlResource.uuid, data);
        MessagePlugin.success('更新成功');
      } else {
        await createUrlResource(data);
        MessagePlugin.success('创建成功');
      }
      setFormVisible(false);
      getList();
    } catch (error) {
      MessagePlugin.error(editingUrlResource?.uuid ? '更新失败' : '创建失败');
    }
  };

  const getMethodColor = (method: string) => {
    switch (method) {
      case 'GET':
        return 'success';
      case 'POST':
        return 'primary';
      case 'PUT':
        return 'warning';
      case 'DELETE':
        return 'danger';
      case 'PATCH':
        return 'default';
      default:
        return 'default';
    }
  };

  useEffect(() => {
    getList();
  }, [pagination.current, pagination.pageSize, searchUrl, searchMethod, searchModule]);

  return (
    <Card title="URL资源管理">
      <div style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 16, marginBottom: 16 }}>
          <Input
            placeholder="搜索URL"
            value={searchUrl}
            onChange={(value) => setSearchUrl(value)}
            style={{ width: 150 }}
          />
          <DictionarySelect
            dictType="http_method"
            value={searchMethod}
            onChange={setSearchMethod}
            placeholder="选择方法"
            clearable={true}
            style={{ width: 120 }}
          />
          <Input
            placeholder="搜索模块"
            value={searchModule}
            onChange={(value) => setSearchModule(value)}
            style={{ width: 150 }}
          />
          <Button theme="primary" onClick={getList}>
            查询
          </Button>
          <Button theme="default" icon={<RefreshIcon />} onClick={getList}>
            刷新
          </Button>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button theme="primary" icon={<AddIcon />} onClick={handleCreate}>
            新增URL资源
          </Button>
        </div>
      </div>

      <Table
        data={urlResourceList}
        rowKey="uuid"
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showJumper: true,
          onChange: (pageInfo) => {
            setPagination(prev => ({
              ...prev,
              current: pageInfo.current,
              pageSize: pageInfo.pageSize,
            }));
          },
        }}
        columns={[
          {
            colKey: 'url',
            title: 'URL路径',
            width: 300,
          },
          {
            colKey: 'method',
            title: '请求方法',
            width: 120,
            cell: ({ row }) => (
              <Tag theme={getMethodColor(row.method) as any}>
                {row.method}
              </Tag>
            ),
          },
          {
            colKey: 'module',
            title: '所属模块',
            width: 150,
          },
          {
            colKey: 'description',
            title: '描述',
            width: 200,
          },
          {
            colKey: 'createTime',
            title: '创建时间',
            width: 180,
            cell: ({ row }) => formatTime(row.createTime || ''),
          },
          {
            colKey: 'operation',
            title: '操作',
            width: 150,
            cell: ({ row }) => (
              <div style={{ display: 'flex', gap: 8 }}>
                <Button
                  theme="primary"
                  variant="text"
                  icon={<EditIcon />}
                  onClick={() => handleEdit(row)}
                >
                  编辑
                </Button>
                <Button
                  theme="danger"
                  variant="text"
                  icon={<DeleteIcon />}
                  onClick={() => handleDelete(row)}
                >
                  删除
                </Button>
              </div>
            ),
          },
        ]}
      />

      <UrlResourceForm
        visible={formVisible}
        onClose={() => setFormVisible(false)}
        onSubmit={handleSubmit}
        initialData={editingUrlResource}
        title={title}
      />
    </Card>
  );
}